import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { Constants } from '@/constants/constants';
import { MenuTypeEnum, SysMenu, useAuth, useMenu } from 'pf-component';
import { isNull } from '@/constants/util/objects-utils';
import store from '@/store';

const routesDatas: Array<RouteRecordRaw> = [
  {
    path: process.env.VUE_APP_REDIRECT_PATH || '',
    // name: 'Callback',
    component: () => import(/* webpackChunkName: "Main" */ '@/views/callback/Callback.vue')
  },
  {
    path: '/create-fc-form-config',
    name: 'CreateFcFormConfigWrapper',
    component: () => import(/* webpackChunkName: "Main" */ '@/views/Main.vue'),
    children: [
      {
        path: '',
        name: 'CreateFcFormConfig',
        component: () =>
          import(
            /* webpackChunkName: "Main" */ '@/views/page-config/form-designer/FcDesignerWrapper.vue'
          ),
        meta: { title: '创建Fc表单', activeMenu: '/page-config/form-designer-fc' },
        // props: true // TODO 在vue-router4.1.4之后，使用name跳转路由，传递params参数的功能失效了
        props: route => {
          const params: any = {};
          Object.keys(route.query).forEach(key => {
            params[key] = route.query[key];
          });
          return params;
        }
      }
    ]
  },
  {
    path: '/create-form-config',
    name: 'CreateFormConfigWrapper',
    component: () => import(/* webpackChunkName: "Main" */ '@/views/Main.vue'),
    children: [
      {
        path: '',
        name: 'CreateFormConfig',
        component: () =>
          import(/* webpackChunkName: "Main" */ '@/views/page-config/form/CreateFormConfig.vue'),
        meta: { title: '创建表单', activeMenu: '/page-config/form' },
        // props: true // TODO 在vue-router4.1.4之后，使用name跳转路由，传递params参数的功能失效了
        props: route => {
          const params: any = {};
          Object.keys(route.query).forEach(key => {
            params[key] = route.query[key];
          });
          return params;
        }
      }
    ]
  },
  {
    path: '/create-table-config',
    name: 'CreateTableConfigWrapper',
    component: () => import(/* webpackChunkName: "Main" */ '@/views/Main.vue'),
    children: [
      {
        path: '',
        name: 'CreateTableConfig',
        component: () =>
          import(/* webpackChunkName: "Main" */ '@/views/page-config/table/CreateTableConfig.vue'),
        meta: { title: '创建表格', activeMenu: '/page-config/table' },
        // props: true // TODO 在vue-router4.1.4之后，使用name跳转路由，传递params参数的功能失效了
        props: route => {
          const params: any = {};
          Object.keys(route.query).forEach(key => {
            params[key] = route.query[key];
          });
          return params;
        }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    component: () => import(/* webpackChunkName: "Main" */ '@/views/404/404.vue')
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes: routesDatas
});
const { hasToken, authCode } = useAuth();
router.beforeEach(async (to, from, next) => {
  if (!hasToken() && Constants.PERMITALL.findIndex(path => to.path === path) === -1) {
    authCode();
    // KC()
    //   .then((res: boolean) => {
    //     if (res) {
    //       next();
    //     }
    //   })
    //   .catch(err => console.error(err));
  } else {
    if (!init) {
      // 手动刷新页面的情况
      const menus = store.getters['menus/allMenus'];
      initRouterForMenu(menus);
      await router.push(to); // 重新触发进入路由
    } else {
      next();
    }
  }
});
export default router;

let init = false;
export const initRouterForMenu = (menus: SysMenu[]) => {
  /*router.removeRoute('Main');
    router.addRoute({
    path: '/main',
    name: 'Main',
    component: () => import(/!* webpackChunkName: "Main" *!/ '@/views/Main.vue'),
    children: [
      /!*{
        path: "test",
        name: "Test",
        component: () => import(/!* webpackChunkName: "Main" *!/ "@/views/test/Test.vue")
      },
      ...dcmsRouterInfo,
      ...systemRouter,
      ...pageConfigRouter,
      ...appRouter,
      ...financeRouter*!/
    ]
  });
  const routes: Array<RouteRecordRaw> = [];
  transMenus(routes, '/main', menus);
  routes.forEach(r => router.addRoute('Main', r));*/
  const { buildRoutes } = useMenu();
  menus
    .map(menu => buildRoutes(menu, loadComp))
    .filter(v => !!v)
    .forEach(route => {
      route.path = '/' + route.path;
      router.hasRoute(route.name) && router.removeRoute(route.name);
      router.addRoute(route);
    });
  init = true;
};

const loadComp = (component: string) => {
  if (component === 'Layout') {
    return () => import(/* webpackChunkName: "Main" */ '@/views/Main.vue');
  } else {
    return () => import(/* webpackChunkName: "View" */ `@/views/${component}`);
  }
};
